import imaplib
import email
from email.header import decode_header

# QQ邮箱IMAP服务器地址
IMAP_SERVER = 'imap.qq.com'
# 你的QQ邮箱账号（请替换）
EMAIL_ACCOUNT = '573561243@qq.com'
# 授权码（请替换为你自己的授权码）
EMAIL_PASSWORD = 'lknpxncajrbibfbe'

def connect_to_email():
    """连接到IMAP服务器并登录"""
    try:
        mail = imaplib.IMAP4_SSL(IMAP_SERVER)
        mail.login(EMAIL_ACCOUNT, EMAIL_PASSWORD)
        print("登录成功")
        return mail
    except Exception as e:
        print(f"登录失败: {e}")
        raise

def parse_email(msg):
    """解析邮件内容，返回发件人和主题"""
    email_info = {
        "subject": "",
        "from": ""
    }

    # 解析主题
    subject = decode_header(msg.get("Subject", ""))[0]
    if isinstance(subject[0], bytes):
        email_info["subject"] = subject[0].decode(subject[1] or "utf-8")
    else:
        email_info["subject"] = subject[0]

    # 解析发件人
    from_header = msg.get("From", "")
    email_info["from"] = email.utils.parseaddr(from_header)[1]  # 提取邮箱地址

    return email_info

def fetch_unread_emails(mail):
    """获取所有未读邮件并分页处理"""
    try:
        # 选择收件箱
        status, _ = mail.select("inbox", readonly=True)
        if status != "OK":
            print("无法选择收件箱")
            return

        # 搜索未读邮件
        status, messages = mail.search(None, "UNSEEN")
        if status != "OK":
            print("搜索未读邮件失败")
            return

        mail_ids = messages[0].split()
        total_emails = len(mail_ids)
        print(f"共找到 {total_emails} 封未读邮件")

        # 分页获取（每次取20封）
        page_size = 20
        for i in range(0, total_emails, page_size):
            start = i + 1
            end = min(i + page_size, total_emails)
            status, msg_data = mail.fetch(f"{start}:{end}", "(RFC822)")
            if status != "OK":
                print(f"获取第 {start}-{end} 封未读邮件失败")
                continue

            for response in msg_data:
                if isinstance(response, tuple):
                    msg = email.message_from_bytes(response[1])
                    email_info = parse_email(msg)
                    print(f"发件人: {email_info['from']}")
                    print(f"主题: {email_info['subject']}")
                    print("-" * 50)

    except Exception as e:
        print(f"获取未读邮件失败: {e}")
    finally:
        mail.close()
        mail.logout()
        print("已退出邮箱")

if __name__ == "__main__":
    try:
        mail = connect_to_email()
        fetch_unread_emails(mail)
    except Exception as e:
        print(f"程序出错: {e}")